package com.cdtu.store.item.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cdtu.store.common.entity.CategoryEntity;
import com.cdtu.store.common.entity.SkuEntity;
import com.cdtu.store.common.entity.SpuDetailEntity;
import com.cdtu.store.common.entity.SpuEntity;
import com.cdtu.store.common.utils.PageUtils;
import com.cdtu.store.common.utils.Query;
import com.cdtu.store.item.dao.SpuDao;
import com.cdtu.store.item.service.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.*;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * @author dongyuhao
 */
@Slf4j
@Service("goodsService")
@Transactional
public class GoodsServiceImpl extends ServiceImpl<SpuDao, SpuEntity> implements GoodsService{
    @Autowired
    private SpuService spuService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private BrandService brandService;
    @Autowired
    private SpuDetailService spuDetailService;
    @Autowired
    private SkuService skuService;
    @Autowired
    private AmqpTemplate amqpTemplate;
    @Override
    public PageUtils list(Map<String, Object> params) {
        IPage<SpuEntity> spuPages = this.page(new Query<SpuEntity>().getPage(params),null);
        List<SpuEntity> list = spuPages.getRecords();
        list.forEach((spuBo ->{
            List<CategoryEntity> CategoryEntitys = categoryService.listByIds(Arrays.asList(spuBo.getCid1(), spuBo.getCid2(), spuBo.getCid3()));
            List<String> names = new ArrayList<>();
            CategoryEntitys.forEach(category ->{
                names.add(category.getName());
            });
            spuBo.setCname(StringUtils.join(names,"/"));
            System.out.println(spuBo.getBrandId());
            spuBo.setBname(brandService.getById(spuBo.getBrandId()).getName());
        }));
        return new PageUtils(spuPages);
    }

    @Override
    public boolean saveGoods(SpuEntity spu) {
        //保存spu
        spu.setCreateTime(LocalDate.now().toString());
        spu.setLastUpdateTime(LocalDate.now().toString());
        boolean spuFlag = this.spuService.save(spu);
        //保存spuDetail
        spu.getSpuDetail().setSpuId(spu.getId());
        boolean spuDetailFlag = spuDetailService.save(spu.getSpuDetail());
        AtomicBoolean skuFlag = new AtomicBoolean(true);
        spu.getSkus().forEach(sku ->{
            sku.setSpuId(spu.getId());
            sku.setCreateTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
            sku.setLastUpdateTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
            boolean save = skuService.save(sku);
            if(save == false) {
                skuFlag.set(false);
            }
        });
        //发送消息
        this.sendMessage(spu.getId(),"insert");
        return spuFlag == spuDetailFlag  == skuFlag.get() == true;
    }

    @Override
    public SpuEntity querySpuById(Long id) {
        return this.getById(id);
    }

    @Override
    public SpuEntity getGoods(Long id) {
        SpuEntity spu = this.spuService.getById(id);
        SpuDetailEntity spuDetail = this.spuDetailService.getOne(new QueryWrapper<SpuDetailEntity>().eq("spu_id", id));
        List<SkuEntity> skus = this.skuService.list(new QueryWrapper<SkuEntity>().eq("spu_id", id));
        String brandName = this.brandService.getById(spu.getBrandId()).getName();
        String categoryName = this.categoryService.getById(spu.getCid3()).getName();
        spu.setBname(brandName);
        spu.setCname(categoryName);
        spu.setSpuDetail(spuDetail);
        spu.setSkus(skus);
        return spu;
    }

    @Override
    public void UpdateGoods(SpuEntity spu) {
        //更新spu
        this.spuService.updateById(spu);
        //更新spuDetail
        this.spuDetailService.update(spu.getSpuDetail(),new UpdateWrapper<SpuDetailEntity>().eq("spu_id",spu.getId()));
        //更新sku
        List<SkuEntity> skus = spu.getSkus();
        skus.forEach(sku ->{
            if(sku.getId() != 0){
                this.skuService.updateById(sku);
            }else{
                this.skuService.save(sku);
            }
        });
        //发送消息
        this.sendMessage(spu.getId(),"update");
    }

    @Override
    public void delete(Long[] ids) {
        for(Long id : ids){
            //删除所有的SKU
            this.skuService.remove(new QueryWrapper<SkuEntity>().eq("spu_id",id));
            //删除spudetail
            this.spuDetailService.remove(new QueryWrapper<SpuDetailEntity>().eq("spu_id",id));
            //删除spu
            this.spuService.removeById(id);
            //发送消息
            this.sendMessage(id,"delete");
        }
    }

    private void sendMessage(Long id, String type){
        // 发送消息
        try {
            this.amqpTemplate.convertAndSend("item." + type, id);
        } catch (Exception e) {
            log.error("{}商品消息发送异常，商品id：{}", type, id, e);
        }
    }
    @Override
    public SkuEntity querySkuById(Long id) {
        return this.skuService.getById(id);
    }
}
